package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * saveTimeLine方法异步执行，原理：底层开一个线程去执行该方法
     * @Async 此注解为异步执行注解,开启此注解需要 @EnableAsync 注解来开启异步执行的支持
     * @param userId 自己的ID根据自己的ID去查询tanhua_user表
     * @param publishId 动态的ID,根据此id能够查找到动态
     * @return
     */
    @Async
    public CompletableFuture<String> insertTimeLine(Long userId, ObjectId publishId) {
        //写入好友的时间线表

        try {
            //查询好友列表获取所有好友ID,如果为空则代表无好友,可以直接返回不需要进行时间线表的添加
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> usersList = this.mongoTemplate.find(query, Users.class);
            if (CollUtil.isEmpty(usersList)) {
                //返回成功
                return CompletableFuture.completedFuture("ok");
            }

            //查询到好友ID后根据ID将自己的动态(说说)的动态ID依次写入到好友的时间线表中
            for (Users users : usersList) {
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setDate(System.currentTimeMillis());
                timeLine.setPublishId(publishId);
                timeLine.setUserId(userId);

                //写入数据
                this.mongoTemplate.insert(timeLine, "quanzi_time_line_" + users.getFriendId());
            }
        } catch (Exception e) {
            log.error("写入好友时间线表失败~ userId = " + userId + ", publishId = " + publishId, e);
            return CompletableFuture.completedFuture("error");
        }

        //调用CompletableFuture.complete方法可以立马返回结果
        return CompletableFuture.completedFuture("ok");
    }

}